﻿using Abp;
using Abp.AspNetCore;
using Abp.AspNetCore.Configuration;
using Abp.AutoMapper;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.EntityFrameworkCore;
using Abp.EntityFrameworkCore.Configuration;
using Abp.EntityHistory;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Timing;
using KelonProud.Domain.Entitys;
using KelonProud.Timing;

namespace KelonProud.TableManagement
{
    [DependsOn(typeof(KelonProudModule),
        typeof(AbpKernelModule),
        typeof(AbpAspNetCoreModule),
        typeof(AbpAutoMapperModule),
        typeof(AbpEntityFrameworkCoreModule))]
    public class KelonProudTableModule : AbpModule
    {
        public bool SkipDbContextRegistration { get; set; }

        public override void PreInitialize()
        {
            if (!SkipDbContextRegistration)
            {
                //Configuration.Modules.AbpEfCore().AddDbContext<TableManagementDbContext>(options =>
                //{
                //    if (options.ExistingConnection != null)
                //    {
                //        TableDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
                //    }
                //    else
                //    {
                //        TableDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
                //    }
                //});
            }

            Configuration.Modules.AbpAspNetCore()
                .CreateControllersForAppServices(
                    typeof(KelonProudTableModule).GetAssembly(), "table", false
                );

            //实体历史
            Configuration.EntityHistory.Selectors.Add(new NamedTypeSelector("Kelon.AuditEntity", 
                type => typeof(IAuditEntity).IsAssignableFrom(type)));


            Configuration.ReplaceService<IEntityHistoryStore, EntityHistoryStore>(DependencyLifeStyle.Singleton);
        }

        public override void Initialize()
        {
            var thisAssembly = typeof(KelonProudTableModule).GetAssembly();

            IocManager.RegisterAssemblyByConvention(thisAssembly);

            Configuration.Modules.AbpAutoMapper().Configurators.Add(
                // Scan the assembly for classes which inherit from AutoMapper.Profile
                cfg => cfg.AddProfiles(thisAssembly)
            );
        }

        public override void PostInitialize()
        {
            IocManager.Resolve<AppTimes>().StartupTime = Clock.Now;
        }
    }
}
